home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr26 / netprog.zip / NETPROG.TAR / net.s5 / udpserv.c < prev   
C/C++ Source or Header  |  1989-12-17  |  2KB  |  86 lines

  1. /*
  2.  * Example of server using UDP protocol.
  3.  */
  4.  
  5. #include    "inet.h"
  6.  
  7. main(argc, argv)
  8. int    argc;
  9. char    *argv[];
  10. {
  11.     int            tfd;
  12.     struct sockaddr_in    serv_addr;
  13.     struct t_bind        req;
  14.  
  15.     pname = argv[0];
  16.  
  17.     /*
  18.      * Open a UDP endpoint.
  19.      */
  20.  
  21.     if ( (tfd = t_open(DEV_UDP, O_RDWR, (struct t_info *) 0)) < 0)
  22.         err_dump("server: can't t_open %s", DEV_UDP);
  23.  
  24.     /*
  25.      * Bind our local address so that the client can send to us.
  26.      */
  27.  
  28.     bzero((char *) &serv_addr, sizeof(serv_addr));
  29.     serv_addr.sin_family      = AF_INET;
  30.     serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  31.     serv_addr.sin_port        = htons(SERV_UDP_PORT);
  32.  
  33.     req.addr.maxlen = sizeof(serv_addr);
  34.     req.addr.len    = sizeof(serv_addr);
  35.     req.addr.buf    = (char *) &serv_addr;
  36.     req.qlen        = 5;
  37.  
  38.     if (t_bind(tfd, &req, (struct t_bind *) 0) < 0)
  39.         err_dump("server: can't t_bind local address");
  40.  
  41.     echo(tfd);        /* do it all */
  42.         /* NOTREACHED */
  43. }
  44.  
  45. /*
  46.  * Read the contents of the socket and write each line back to
  47.  * the sender.
  48.  */
  49.  
  50. echo(tfd)
  51. int    tfd;
  52. {
  53.     int            n, flags;
  54.     char            line[MAXLINE];
  55.     char            *t_alloc();
  56.     struct t_unitdata    *udataptr;
  57.  
  58.     /*
  59.      * Allocate memory for the t_unitdata structure and the address field
  60.      * in that structure.  This allows any size of address to be handled
  61.      * by this function.
  62.      */
  63.  
  64.     udataptr = (struct t_unitdata *) t_alloc(tfd, T_UNITDATA, T_ADDR);
  65.     if (udataptr == NULL)
  66.         err_dump("server: t_alloc error for T_UNITDATA");
  67.  
  68.     for ( ; ; ) {
  69.         /*
  70.          * Read a message from the socket and send it back
  71.          * to whomever sent it.
  72.          */
  73.  
  74.         udataptr->opt.maxlen   = 0;    /* don't care about options */
  75.         udataptr->opt.len      = 0;
  76.         udataptr->udata.maxlen = MAXLINE;
  77.         udataptr->udata.len    = MAXLINE;
  78.         udataptr->udata.buf    = line;
  79.         if (t_rcvudata(tfd, udataptr, &flags) < 0)
  80.             err_dump("server: t_rcvudata error");
  81.  
  82.         if (t_sndudata(tfd, udataptr) < 0)
  83.             err_dump("server: t_sndudata error");
  84.     }
  85. }
  86.